package ing.gzq.websocket;

import com.alibaba.fastjson.JSON;
import ing.gzq.model.Message;
import ing.gzq.model.Room;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

import static ing.gzq.websocket.WebsocketContainer.getRoomById;

@Component
public class WebsocketSupport {


    static Log logger = LogFactory.getLog(WebsocketSupport.class);
     /*
        0 : 正常
        1 : 找不到房间
        2 : 找不到人
     */

    public int sendMessageToTeacher(Long roomId, Message message)  {
        try {
            Room room = getRoomById(roomId);
            if (room == null) return 1;
            WebSocketSession session = room.getTeacherSession();
            if (session == null) return 2;
            session.sendMessage(new TextMessage(JSON.toJSONString(message)));
            return 0;
        }catch (IOException ex){
            ex.printStackTrace();
            logger.error("web socket error send message to teacher");
            throw new RuntimeException(ex);
        }
    }

    public int sendMessageToStudents(Long roomId, Message message)  {
        try {
            Room room = getRoomById(roomId);
            if (room == null) return 1;
            room.sendToStudents(JSON.toJSONString(message));
            return 0;
        }catch (IOException ex){
            ex.printStackTrace();
            logger.error("web socket error send message to students");
            throw new RuntimeException(ex);
        }
    }

    public int sendMessageToAll(Long roomId, Message message) {
        try {
            Room room = getRoomById(roomId);
            if (room == null) return 1;
            room.sendToAll(JSON.toJSONString(message));
            return 0;
        }catch (IOException ex){
            ex.printStackTrace();
            logger.error("web socket error send message to all");
            throw new RuntimeException(ex);
        }
    }
}
